import React, { Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import qs from 'qs';
import _ from 'lodash';

import {
  Col,
  Row,
  Card,
  Select,
  Button,
} from 'antd';

import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import '@ant-design/compatible/assets/index.css';

import { addTab } from '@/utils/utils';


const FormItem = Form.Item;
const { Option } = Select;

interface TableProps extends FormComponentProps {
  dispatch: Dispatch;
  INITINFO: any;
  sortingExpress: any;
}

interface TableState {
  formValues: any;
  new_sortingExpress: any,
}


const gridStyle = {
  width: '70%',
  display: 'flex',
  flexBasis: '20%',
  justifyContent: 'space-between',
  boxShadow: 'none',
};

const textColor = [
  {
    key: '1',
    color: '#000000',
    borderColor: '#cccccc',
  },
  {
    key: '2',
    color: '#FF0000',
    borderColor: '#cccccc',
  },
  {
    key: '3',
    color: '#0000FF',
    borderColor: '#cccccc',
  },
  {
    key: '4',
    color: '#008000',
    borderColor: '#cccccc',
  },
  {
    key: '5',
    color: '#FFA500',
    borderColor: '#cccccc',
  },
];

@connect(({
  tookManagementSetting: { sortingExpress },
  common: { INITINFO },
}: any) => ({
  sortingExpress,
  INITINFO,
}))

class Setting extends React.Component<TableProps, TableState> {
  state: TableState = {
    formValues: {},
    new_sortingExpress: {},
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });

    const stateToProps = {
      ...state,
      formValues: query,
    };

    if (!Object.keys(state.new_sortingExpress).length) {
      stateToProps.new_sortingExpress = props.sortingExpress;
    }

    return stateToProps;
  }

  componentDidMount() {
    this.fetchLogisList();

    const { formValues } = this.state;
    if (Object.keys(formValues).length) {
      this.setFieldsValue();
      this.fetchSortingList();
    }
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues } = this.state;
    if (Object.keys(formValues).length && !_.isEqual(formValues, prevState.formValues)) {
      this.setFieldsValue();
      this.fetchSortingList();
    }
  }

  // 获取物流中心列表
  fetchLogisList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchLogisList',
    });
  }

  // 获取数据
  fetchSortingList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tookManagementSetting/fetch',
      payload: this.getQueryParams(),
    });
  };

  // 获取查询参数
  getQueryParams = () => {
    const { formValues } = this.state;
    return formValues;
  };

  // 设置表单值
  setFieldsValue = () => {
    const { formValues } = this.state;
    const { form } = this.props;

    form.setFieldsValue(formValues);
  }

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form, dispatch } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const query = {
        ...fieldsValue,
      };
      addTab(dispatch, {
        name: '设置',
        url: `/tookDeposit/tookManagement/list/setting?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 选择颜色
   */
  handleChangeColor = (color: string, type: string, index: number) => {
    const { new_sortingExpress } = this.state;

    const expressList = new_sortingExpress[type];

    expressList[index].color = color;
    new_sortingExpress[type] = expressList;

    this.setState({ new_sortingExpress });
  };

  /**
   * 点击添加边框
   */
  handleAddBorder = (event: any) => {
    const { target } = event;
    const current = event.currentTarget;
    for (let i = 0; i < current.children.length; i += 1) {
      current.children[i].classList.remove('border');
    }
    target.classList.add('border');
  };

  /**
   * 上移下移 inndex:下标  up:上移下移  type:上门取件还是门店寄件
   */
  handleUpDown = (index: number, up: number, type: string) => {
    const { new_sortingExpress } = this.state;

    const expressList = new_sortingExpress[type];

    const curList = expressList[index];

    expressList.splice(index, 1);
    if (up === 0) {
      expressList.splice(index - 1, 0, curList);
    } else {
      expressList.splice(index + 1, 0, curList);
    }
    new_sortingExpress[type] = expressList;

    this.setState({ new_sortingExpress });
  };

  /**
   * 保存
   */
  handleSaveSorting = () => {
    const { formValues: params, new_sortingExpress } = this.state;

    const data = Object.keys(new_sortingExpress)
      .reduce((origin: any, key: string) => {
        const expressList = new_sortingExpress[key]
          .reduce((sub_origin: any, item: any, index: number) => {
            item.type = Number(key);
            item.sorting = index + 1;

            sub_origin.push(item);
            return sub_origin;
          }, []);

        origin = [...origin, ...expressList];
        return origin;
      }, []);

    params.data = data;

    const { dispatch } = this.props;
    dispatch({
      type: 'tookManagementSetting/saveSorting',
      payload: params,
    });
  };

  /**
   * 取消
   */
  handleCancel = () => {
    const { form } = this.props;
    form.resetFields();
    router.push('/tookDeposit/tookManagement/list/setting');
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      INITINFO: { logisList },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <FormItem label="物流中心" colon={false}>
              {getFieldDecorator('logisId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {logisList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={3} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };


  render() {
    const { formValues, new_sortingExpress } = this.state;

    const sortingExpress_keys = Object.keys(new_sortingExpress);
    const sortingExpress_values: any = Object.values(new_sortingExpress)[0];
    const sorting_values = Array.isArray(sortingExpress_values)
      && sortingExpress_values.length !== 0;

    return (
      <Fragment>
        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>
        <div className="margin20" style={{ backgroundColor: '#fff' }}>
          {Object.keys(formValues).length === 0 && <Card><div>请选择物流中心!</div></Card>}

          {
            Object.keys(formValues).length !== 0 && sorting_values
              ? (
                sortingExpress_keys.map((title: any) => (
                  <Card
                    bordered={false}
                    key={title}
                    title={title === '7' ? '上门取件快递公司设置' : '门店寄件快递公司排序设置'}
                    className="marginB20 card_paddB0 marginT20"
                  >
                    {
                      new_sortingExpress[title].map((item: any, index: any) => (
                        <Card.Grid style={gridStyle} className="card" key={item.tariffId}>
                          <span
                            style={{ color: `${item.color}` }}
                            className="children_basis"
                          >
                            {item.expressName}
                          </span>
                          <div
                            className="map_color_box children_basis"
                            onClick={this.handleAddBorder}
                          >
                            <span className="marginR40">展示的字体颜色:</span>
                            {
                              textColor.map((color: any) => (
                                <span
                                  className="map_color"
                                  key={color.key}
                                  style={{ background: `${color.color}` }}
                                  onClick={() => this.handleChangeColor(color.color, title, index)}
                                />
                              ))
                            }
                          </div>
                          <div>
                            <Button
                              disabled={index === 0}
                              onClick={() => this.handleUpDown(index, 0, title)}
                            >
                              上移
                            </Button>
                            <Button
                              className="marginL16"
                              disabled={index === new_sortingExpress[title].length - 1}
                              onClick={() => this.handleUpDown(index, 1, title)}
                            >
                              下移
                            </Button>
                          </div>
                        </Card.Grid>
                      ))
                    }
                  </Card>
                ))
              )
              : <Card style={{ display: Object.keys(formValues).length === 0 ? 'none' : 'block' }}><div>该物流中心未配置快递资费，请配置资费后再进行顺序设置</div></Card>
          }

          {
            Object.keys(formValues).length !== 0 && sorting_values && (
              <Card>
                <Button
                  type="primary"
                  htmlType="submit"
                  className="smallButton"
                  onClick={this.handleSaveSorting}
                >
                  保存
                </Button>
                <Button
                  className="smallButton marginL24"
                  onClick={this.handleCancel}
                >
                  取消
                </Button>
              </Card>
            )
          }
        </div>
      </Fragment>
    );
  }
}

export default Form.create<TableProps>()(Setting);
